#include <iostream>
#include <algorithm>
#include "Master.h"

using namespace std;

void *Master::read_ast(void *arg)
{
	void **param = (void**)(arg);
	Master *m = (Master*)(param[0]);
	ast *a = (ast*)(param[1]);
	
	string buf = "", msg = "";
	long size = 0;
	int status = 1;
	
	bool find = false;
	etu e;
	for(vector<etu>::iterator it = m->etus.begin(); it != m->etus.end() && !find; ++it)
	{
		if(it->login == a->etulogin)
		{
			find = true;
			e = (*it);
		}
	}
	
	// Ecoute de la socket de l'étudiant gérer par l'assistant
	while(status > 0)
	{
		status = m->getProto(buf, &e.sock);
		if(buf == "ETUD/AST/MSG")
		{
			status = e.sock.read4(&size);
			status = m->getString(msg, size, &e.sock);
			m->sendProto("ETUD/MSG", &a->sock);
			a->sock.send4(msg.size());
			a->sock.sendMsg(msg.c_str(), msg.size());
		}
	}
}

void *Master::manageAst(void *arg)
{
	void **param = (void**)(arg);
	Master *m = (Master*)(param[0]);
	ast *a = (ast*)(param[1]);
	
	pthread_t read_ast_thread;
	pthread_create(&read_ast_thread, NULL, read_ast, (void*)param);
	
	bool find = false;
	etu *e;
	for(vector<etu>::iterator it = m->etus.begin(); it != m->etus.end() && !find; ++it)
	{
		if(it->login == a->etulogin)
		{
			find = true;
			e = &(*it);
		}
	}
	
	int status = 1;
	long size = 0;
	string buf = "", msg = "";
	// On prend la main sur l'activité en cours avec l'étudiant
	pthread_mutex_lock(&e->writing);
	e->isAssistant = true;
	pthread_mutex_unlock(&e->writing);
	while(status > 0)
	{
		status = m->getProto(buf, &a->sock);
		if(buf == "AST/ETU/MSG")
		{
			status = a->sock.read4(&size);
			status = m->getString(msg, size, &a->sock);

			m->sendProto("AST/MSG", &e->sock);
			e->sock.send4(size);
			e->sock.sendMsg(msg.c_str(), size);
		}
	}
	cout << "Deconnexion de " << a->login << endl;
	pthread_cancel(read_ast_thread);
	return NULL;
}
